﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Pages_RM_Receipt : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        handleEditMode();
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (ValidateForm() != "")
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Error", "alert('" + ValidateForm() + "');", true);
            return;
        }
        if (btnSave.CommandArgument == "")
        {
            tbl_rm_receipt model = new tbl_rm_receipt();
            model.RM_Order_Number = ddlRM_Order_Number.SelectedValue;
            model.Quantity_Received = Convert.ToDecimal(txtQuantity_Received.Text.Trim());
            model.Date = txtDate.Text.Trim().toDateTimeWithoutError();
            model.Note = txtNote.Text.Trim();
            model.Bag_Number = txtBag_Number.Text.Trim();
            model.Drum_Number = txtDrum_Number.Text.Trim();
            model.CREATED_BY = User.Identity.Name;
            model.CREATED_DATE = DateTime.Now;



            BLL_tbl_rm_receipt bll = new BLL_tbl_rm_receipt();
            try
            {


                
                bll.insert(model);
                string script = "top.location=" + '"' + HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + Request.RawUrl + '"';

                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Success", "alert('Record Saved Succesfully');", true);
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Postback", script, true);
                return;
            }
            catch (Exception)
            {

                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Error", "alert('Error Occured');", true);
                return;
            }
        }
        else
        {
            tbl_rm_receipt model = new tbl_rm_receipt();
            model.ID = Convert.ToInt32(btnSave.CommandArgument);
            model.RM_Order_Number = ddlRM_Order_Number.SelectedValue;
            model.Quantity_Received = Convert.ToDecimal(txtQuantity_Received.Text.Trim());
            model.Date = txtDate.Text.Trim().toDateTimeWithoutError();
            model.Note = txtNote.Text.Trim();
            model.Bag_Number = txtBag_Number.Text.Trim();
            model.Drum_Number = txtDrum_Number.Text.Trim();
            model.UPDATED_BY = User.Identity.Name;
            model.UPDATED_DATE = DateTime.Now;



            BLL_tbl_rm_receipt bll = new BLL_tbl_rm_receipt();
            bll.update(model);
            btnSave.CommandArgument = "";
            Response.Redirect(Request.Url.AbsolutePath);
        }
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect(Request.Url.AbsolutePath);
    }

    protected void linkDelete_Click(object sender, EventArgs e)
    {
        string id = ((LinkButton)sender).CommandArgument;
        tbl_rm_receipt model = new tbl_rm_receipt();
        model.ID = Convert.ToInt32(id); ;

        BLL_tbl_rm_receipt bll = new BLL_tbl_rm_receipt();
        bll.delete(model);
    }

    protected void linkEdit_Click(object sender, EventArgs e)
    {
        string id = ((LinkButton)sender).CommandArgument;
        Response.Redirect(Request.Url.AbsolutePath + "?editRecord=" + id);
    }


    protected void handleEditMode()
    {
        if (!IsPostBack)
        {
            if (Request.QueryString["editRecord"] != null)
            {
                string id = Request.QueryString["editRecord"];
                BLL_tbl_rm_receipt bll = new BLL_tbl_rm_receipt();
                List<tbl_rm_receipt> list = bll.select(Convert.ToInt32(id));
                foreach (tbl_rm_receipt tbl in list)
                {
                    btnSave.CommandArgument = tbl.ID.ToString();
                    ddlRM_Order_Number.SelectedValue = tbl.RM_Order_Number;
                    txtQuantity_Received.Text = tbl.Quantity_Received.ToString();
                    txtDate.Text = tbl.Date.ToString("yyyy-MM-dd");
                    txtNote.Text = tbl.Note;
                    txtBag_Number.Text = tbl.Bag_Number;
                    txtDrum_Number.Text = tbl.Drum_Number;
                    

                }
            }
        }
    }



    protected void ddlRM_Order_Number_SelectedIndexChanged(object sender, EventArgs e)
    {
        char pad = '0';
        string prefix = "";
        string suffix = "";
        int lastNumber = 1;
        int length = 4;
        if (ddlRM_Order_Number.SelectedIndex <= 0)
        {
            txtQuantity_Received.Text = "";
            txtBag_Number.Text = "";
            txtDrum_Number.Text = "";
            return;
        }
        BLL_tbl_raw_material_order bll = new BLL_tbl_raw_material_order();
        DataTable dt = bll.getQtyForRMOrder();
        if (dt != null)
        {
            DataRow[] dr = dt.Select("RM_ORDER_NUMBER='" + (ddlRM_Order_Number.SelectedItem.ToString()).Trim() + "'");
            if (dr.Length > 0)
            {
                txtQuantity_Received.Text = dr[0]["QUANTITY"].ToString();
                int i = Convert.ToInt32(dr[0]["VESSEL_ID"]);
                BLL_tbl_rm_receipt bllRMReceipt = new BLL_tbl_rm_receipt();
                DataTable dt1 = bllRMReceipt.getBagAndDrumLastNum((ddlRM_Order_Number.SelectedItem.ToString()).Trim());
                if (dt1.Rows.Count > 0 )
                {
                    string Number = (dt1.Rows[0]["Bag_Number"].ToString() + dt1.Rows[0]["Drum_Number"].ToString()).Trim();
                    string [] arr = Number.Split('0');
                    lastNumber = Convert.ToInt32(arr[Convert.ToInt32(arr.Length)-1]) + 1;

                }
                
                
                if (i == 1)
                {
                    prefix = "B-";

                    txtBag_Number.Text = Util.getNextPaddingNumber(pad, prefix, suffix, lastNumber, length);
                    txtDrum_Number.Text = "";

                }
                else
                {
                    prefix = "D-";

                    txtBag_Number.Text = "";
                    txtDrum_Number.Text = Util.getNextPaddingNumber(pad, prefix, suffix, lastNumber, length);
                }
                return;
            }
        }
    }
    protected void ddlRM_Order_Number_DataBound(object sender, EventArgs e)
    {
        ListItem li = new ListItem("--Select--", "0");
        ddlRM_Order_Number.Items.Insert(0, li);
    }

    #region Validate Form

    private string ValidateForm()
    {
        string str = "";
        try
        {
            // Check if Client is Selected 
            if (ddlRM_Order_Number.SelectedIndex == 0)
            {
                return "Please Select RM Order Number";
            }
            if (txtDate.Text == "") return "Please enter Date";
            if (txtNote.Text == "") return "Please enter Note";
            

            return str;
        }
        catch (Exception)
        {

            return "Error in Validation";
        }
        finally
        {
            str = null;
        }
    }

    #endregion
}